var dbConfig = require("./dbConfig.js")
var cacheDB = require("./cacheDB.js")
var util = require("../util/util.js")
var errorLogger = require("pomelo-logger").getLogger("error-log");
module.exports = function(app) {
  return new dbService(app);
};
var dbService = function(app) {
	dbService.app = app
	this.app = app
}
var local = {}
var newAccountList = {}
//连接数据库
dbService.prototype.start = function(cb){
	dbConfig.start(dbService)
	this.app.set("dbService",dbService)
	cb()
}
//开启缓存定时器
dbService.beginCacheDB = function() {
	cacheDB.start(dbService)
}
//写入缓存消息
dbService.writeMessage = function(message,cb) {
	dbService.cacheDB.rpush("gameMessage",message,function(err,data) {
		if(err){
			errorLogger.info("gameMessage error : \n"+err+"\ndata : \n"+data)
			if(cb){
				cb(false)
			}
		}else{
			if(cb){
				cb(true)
			}
		}
	})
}
//新账号处理
local.newAccount = function(player,msg) {
	//判断邀请
	if(msg && msg.inviter && typeof(msg.inviter) == "number" && msg.inviter != player.uid){
		//增加复活次数
		console.log("newAccount : "+player.uid+"  : "+msg.inviter)
		//通知后台
	    var messageInfo = {
	      messageType : "newAccountBindInviter",
	      uid : player.uid,
	      inviter : msg.inviter,
	      time : (new Date()).getTime()
	    }
	    dbService.writeMessage(JSON.stringify(messageInfo))
	    //通知玩家
		var notify = {
			cmd : "newAccountAddPlayCount",
			player : player
		}
		dbService.app.rpc.game.remote.sendByUid(null,msg.inviter,notify,function(){})
		// dbService.app.rpc.db.mail.sendMail(null,msg.inviter,"邀请奖励","您的好友 "+player.nickname+"("+player.uid+") 被邀请加入游戏，您获得了一张闯关卡",{1001 : 1},null)
		//邀请宝箱
		dbService.db.hincrby("game:inviteInfo:"+msg.inviter,"allNum",1,function(err,data) {
			if(data <= 30){
				dbService.db.hset("game:inviteInfo:"+msg.inviter,"award:"+data,true)
			}
		})
		//代理记录玩家列表
		player.time = (new Date()).getTime()
		dbService.db.hset("game:inviteUsers:"+msg.inviter,player.uid,JSON.stringify(player))
		dbService.db.rpush("game:inviteUsersList:"+msg.inviter,player.uid,function(){})
	}
	//领取初始任务
	dbService.app.rpc.db.task.gainFirstTask(null,player.uid,null)
	//欢迎邮件
	dbService.app.rpc.db.mail.sendMail(null,player.uid,"欢迎登陆我爱跑得快","您有一个最高88元的红包，请到app版领取，下载方式：点击游戏首页的\“更多\”-》\“反馈\”按钮，回复：\“1\”",{102 : 2000},null)
}
//每天首次登陆处理
local.dayLogin = function(uid,data) {
	var curDate = util.getDateString()
    //设置登录状态
	dbService.setPlayer(uid,"lastLogin",curDate,function(){
		//更新闯关次数
		dbService.db.hset("gameServer:lotteryCountList",uid,1,function(){})
		//刷新每日任务
		dbService.app.rpc.db.task.refreshTask(null,uid,null)
		//邮件清理
		dbService.app.rpc.db.mail.clearMail(null,uid,null)
		//金币场次数
		dbService.setPlayer(uid,"goldPlayCount",0,function(){})
	    //登陆信息传到后台
	    var messageInfo = {
	      messageType : "login",
	      userInfo : data,
	      time : (new Date()).getTime()
	    }
	    dbService.writeMessage(JSON.stringify(messageInfo))
	})
}
//在线玩家0点自动刷新
dbService.dayOnlineUpdate = function(users) {
	for(var i in users){
		let index = i
		dbService.db.hgetall("nn:acc:"+index,function(err,data) {
			local.dayLogin(index,data)
		})
	}
}
//获取队列
dbService.getList = function(str,begin,len,cb) {
	var info = {
		len : 0,
		data : []
	}
	dbService.db.llen(str,function(err,data) {
		if(err || !data){
			cb(true,info)
			return
		}
		info.len = data
		dbService.db.lrange(str,-begin-len+1,-begin,function(err,data) {
			if(err || !data){
				cb(true,info)
			}else{
				info.data = data
				cb(true,info)
			}
		})
	})
}
//根据unionid获取uid
dbService.getUidByUnionid = function(unionid,cb) {
	dbService.db.get("nn:uidMap:"+unionid,function(err,data) {
		if(err || !data){
			cb(false)
		}else{
			cb(true,data)
		}
	})
}
//检查账号，不存在则创建,存在则更新
dbService.checkAccount = function(result,msg,cb) {
	dbService.getUidByUnionid(result.unionid,function(flag,data) {
		if(flag){
			result.playerId = parseInt(data)
			var info = {
				nickname : result.nickname,
				head : result.headimgurl,
				sex : result.sex
			}
			dbService.updateAccount(result.playerId,info)
			if(cb){
				cb(true)
			}
		}else{
			result.inviter = msg.inviter
			dbService.createAccount(result,function(flag,player) {
				if(flag){
					local.newAccount(player,msg)
				}
				cb(flag)
			})
		}
	})
}
//先获取UID再获取玩家信息
dbService.getPlayerInfo = function(unionid,cb) {
	dbService.getUidByUnionid(unionid,function(flag,data) {
		if(flag){
			dbService.getPlayerInfoByUid(data,cb)
		}else{
			cb(false)
		}
	})
}
//根据UID获取玩家信息
dbService.getPlayerInfoByUid = function(uid,cb) {
	dbService.db.hgetall("nn:acc:"+uid,function(err,data) {
		if(err || !data){
			console.log(err)
			cb(false)
			return
		}
		//数据更新
		var curDate = util.getDateString()
		if(data.lastLogin != curDate){
			var curDate = util.getDateString()
			data.lastLogin = curDate
			data.goldPlayCount = 0
		    //更新每日登陆
			local.dayLogin(uid,data)
		}
		if(newAccountList[uid]){
			console.log("newAccountList : ",newAccountList)
			data.newAccount = true
			delete newAccountList[uid]
		}
		cb(data)
	})
}
//获取玩家基本信息
dbService.getBasicInfo = function(uid,cb) {
	var arr = ["nickname","head","gold","diamond","cScore","phone","referrer"]
	dbService.db.hmget("nn:acc:"+uid,arr,function(err,data) {
		var info = {}
		for(var i = 0;i < arr.length;i++){
			info[arr[i]] = data[i]
		}
		cb(true,info)
	})
}
//获取玩家简单信息
dbService.getSimpleInfo = function(uid,cb) {
	var arr = ["nickname","head"]
	dbService.db.hmget("nn:acc:"+uid,arr,function(err,data) {
		var info = {}
		for(var i = 0;i < arr.length;i++){
			info[arr[i]] = data[i]
		}
		cb(true,info)
	})
}
//创建账号
dbService.createAccount = function(result,cb) {
	dbService.db.incrby("nn:acc:lastid",1,function(err,data) {
		var uid = parseInt(data)
		var info = {
			uid : uid,
			nickname : result.nickname,
			head : result.headimgurl,
			diamond : 0,
			cScore : 10000,
			sex : result.sex || 0,
			limits : 0,
			freeze : 0,
			gold : 0,
			contorl : 0,
			unionid : result.unionid,
			openid : result.openid,
			lastLogin : 0,
			inviter : result.inviter
		}
		if(result.phone){
			info.phone = result.phone
			dbService.db.hmset("game:phoneMap",result.phone,uid)
		}
		if(result.referrer){
			info.referrer = result.referrer
		}
		dbService.db.hmset("nn:acc:"+uid,info,function(err,data) {
			if(err){
				console.log("创建账号错误 : "+err)
				cb(false)
			}else{
				dbService.db.set("nn:uidMap:"+result.unionid,uid)
				var player = {
					uid : uid,
					nickname : result.nickname,
					head : result.headimgurl
				}
				cb(true,player)
			}
		})
		var playerRed = {
			allValue : 0
		}
		playerRed[util.getDateString(0)] = "none"
		playerRed[util.getDateString(1)] = "none"
		playerRed[util.getDateString(2)] = "none"
		playerRed[util.getDateString(3)] = "none"
		playerRed[util.getDateString(4)] = "none"
		playerRed[util.getDateString(5)] = "none"
		playerRed[util.getDateString(6)] = "none"
		dbService.db.hmset("game:newPlayerRed:"+uid,playerRed)
	    //新账号创建传到后台
	    info.ip = result.ip
	    info.channel_appid = result.channel_appid || false
	    var messageInfo = {
	      messageType : "createAccount",
	      userInfo : info,
	      time : (new Date()).getTime()
	    }
	    dbService.writeMessage(JSON.stringify(messageInfo))
		newAccountList[uid] = true
	})
}
//更新账号信息
dbService.updateAccount = function(uid,info,cb) {
	dbService.db.hmset("nn:acc:"+uid,info,function(err,data) {
		if(err){
			console.log("更新账号信息错误 : "+err)
		}
	})
}
//设置数据
dbService.setPlayer = function(uid,name,value,cb) {
	var cmd = "nn:acc:"+uid
	dbService.db.hset(cmd,name,value,function(flag) {
		if(cb){
			if(!flag){
				cb(true)
			}else{
				cb(false)
			}
		}
	})
}
//number数据改变
dbService.incrbyPlayer = function(uid,name,value,cb) {
	var cmd = "nn:acc:"+uid
	dbService.db.hincrby(cmd,name,value,function(err,curValue) {
		if(err){
			cb(false)
			return
		}
		if(curValue < 0){
			dbService.db.hset(cmd,name,0,function(){})
		}
		cb(true,curValue)
	})
}
//获取number数据
dbService.getPlayer = function(uid,name,cb) {
	var cmd = "nn:acc:"+uid
	dbService.db.hget(cmd,name,function(err,data) {
		if(err || !data){
			if(cb){
				cb(0)
			}
		}else{
			if(cb){
				cb(parseInt(data))
			}
		}
	})
}
//获取string数据
dbService.getPlayerString = function(uid,name,cb) {
	var cmd = "nn:acc:"+uid
	dbService.db.hget(cmd,name,function(err,data) {
		//console.log(cmd + "  data : "+data)
		if(err){
			if(cb){
				cb(false)
			}
		}else{
			if(cb){
				cb(data)
			}
		}
	})
}
//设置object数据
dbService.setPlayerObject = function(uid,name,value,cb) {
	var cmd = "nn:acc:"+uid
	value = JSON.stringify(value)
	dbService.db.hset(cmd,name,value,function(flag) {
		if(cb){
			cb(flag)
		}
	})
}
//获取object数据
dbService.getPlayerObject = function(uid,name,cb) {
	var cmd = "nn:acc:"+uid
	dbService.db.hget(cmd,name,function(err,data) {
		//console.log(cmd + "  data : "+data)
		if(err){
			if(cb){
				cb(false)
			}
		}else{
			if(cb){
				data = JSON.parse(data)
				cb(data)
			}
		}
	})
}
//获取物品数量
dbService.getItem = function(uid,itemId,cb) {
	switch(itemId){
		case 101:
			//钻石
			dbService.getPlayer(uid,"diamond",cb)
		break
		case 102:
			//金币
			dbService.getPlayer(uid,"gold",cb)
		break
		case 103:
			//余额
			dbService.db.hget("game:account:balance",uid,function(err,data) {
				if(!err && data){
					cb(parseFloat(data))
				}else{
					cb(0)
				}
			})
		break
		case 104:
			//提现冻结余额
			dbService.db.hget("game:account:freezeBalance",uid,function(err,data) {
				if(!err && data){
					cb(parseFloat(data))
				}else{
					cb(0)
				}
			})
		break
		case 105:
			dbService.getPlayer(uid,"cScore",cb)
		break
		case 201:
			//抽奖次数
			dbService.db.hget("gameServer:lotteryCountList",uid,function(err,data) {
				if(!err && data){
					cb(parseInt(data))
				}else{
					cb(0)
				}
			})
		break
		case 202:
			//闯关复活次数
			dbService.db.hget("game:checkpoint:playCount",uid,function(err,data) {
				if(!err && data){
					cb(parseInt(data))
				}else{
					cb(0)
				}
			})
		break
		default :
			dbService.db.hget("game:bagList:"+uid,itemId,function(err,data) {
				if(!err && data){
					cb(parseInt(data))
				}else{
					cb(0)
				}
			})
		return
	}
}
//获取奖励
dbService.addItem = function(uid,itemId,count,cb) {
	local.addItem(uid,itemId,count,false,cb)
}
//保存奖励附带原因
dbService.addItemReason = function(uid,itemId,count,reason,cb) {
	local.addItem(uid,itemId,count,reason,cb)
}
local.addItem = function(uid,itemId,count,reason,cb) {
	switch(itemId){
		case 101:
			//钻石
			dbService.incrbyPlayer(uid,"diamond",count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 102:
			//金币
			dbService.incrbyPlayer(uid,"gold",count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 103:
			//余额
			dbService.db.hincrbyfloat("game:account:balance",uid,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 104:
			//提现冻结余额
			dbService.db.hincrbyfloat("game:account:freezeBalance",uid,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 105:
			//比赛场积分
			dbService.incrbyPlayer(uid,"cScore",count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 201:
			//抽奖次数
			dbService.db.hincrby("gameServer:lotteryCountList",uid,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 202:
			//闯关复活次数
			dbService.db.hincrby("game:checkpoint:playCount",uid,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 1001:
			//闯关卡道具
			dbService.db.hincrby("game:bagList:"+uid,itemId,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 1002:
			//记牌器道具
			dbService.db.hincrby("game:bagList:"+uid,itemId,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 1003:
			//参赛券
			dbService.db.hincrby("game:bagList:"+uid,itemId,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 2001:
			//一元话费券
			dbService.db.hincrby("game:bagList:"+uid,itemId,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 2010:
			//百元京东E卡
			dbService.db.hincrby("game:bagList:"+uid,itemId,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		case 2011:
			//千元京东E卡
			dbService.db.hincrby("game:bagList:"+uid,itemId,count,local.addItemCB(uid,itemId,count,reason,cb))
		break
		default :
			console.log("default itemId : "+itemId)
			dbService.db.hincrby("game:bagList:"+uid,itemId,count,local.addItemCB(uid,itemId,count,reason,cb))
		return
	}
}
//领取完奖励后通知
local.addItemCB = function(uid,itemId,count,reason,cb) {
	return function(flag,curValue){
		if(flag || flag == null){
			switch(itemId){
				case 201:
					if(curValue > 10){
						curValue = 10
						dbService.db.hset("gameServer:lotteryCountList",uid,10,function(err,data){})
					}
				break
				default:
					//通知后台
				    var messageInfo = {
				      	messageType : "itemUpdate",
				      	uid : uid,
				      	itemId : itemId,
						change : parseFloat(count),
						curValue : parseFloat(curValue),
						reason : reason,
				      	time : (new Date()).getTime()
				    }
				    dbService.writeMessage(JSON.stringify(messageInfo))
			}
			//通知更新
			var notify = {
				"cmd" : "itemChange",
				"itemId" : itemId,
				"change" : count,
				"curValue" : curValue
			}
			dbService.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
			if(cb){
				cb(true,curValue)
			}
		}else{
			if(cb){
				cb(false)
			}
		}
	}
}
//----------------------公告相关----------------------//
//设置公告
dbService.setNotify = function(notify,cb) {
	var cmd = "gameServer:notifys"
	//console.log(JSON.stringify(notify))
	dbService.db.set(cmd,JSON.stringify(notify),function(flag) {
		if(cb){
			cb(flag)
		}
	})
}
//获取公告
dbService.getNotify = function(cb) {
	var cmd = "gameServer:notifys"
	dbService.db.get(cmd,function(err,data) {
		cb(JSON.parse(data))
	})
}